import json
import os.path

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.gzip import GZipMiddleware
from starlette.responses import FileResponse
from starlette.staticfiles import StaticFiles

app = FastAPI()
app.mount("/assets", StaticFiles(directory="ui/assets"), name="assets")
app.add_middleware(GZipMiddleware, minimum_size=1000)

available_data_files = [
    './assets/view_data.json',
    'data.json',
]
discipline_data = None
for data_file in available_data_files:
    if os.path.exists(data_file):
        discipline_data = json.load(open(data_file, 'rb'))
        break

if not discipline_data:
    raise RuntimeError('No data file found')


@app.get("/")
def get_index():
    """
    主页
    """
    return FileResponse('ui/index.html')


@app.get("/favicon.ico")
def get_favicon():
    """
    图标
    """
    return FileResponse('ui/favicon.ico')


@app.get("/api/data")
def get_data():
    """
    获取数据
    """
    return discipline_data


if __name__ == '__main__':
    uvicorn.run('main:app', host="0.0.0.0", port=8000, reload=False)
